<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/6/4
 * Time: 上午9:49
 */

namespace app\common\controller;

use app\common\model\Agent;
use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardGive;
use app\common\model\CardMember;
use app\common\model\CardPaycard;
use app\common\model\CardUserGet;
use app\common\model\Merchant;
use app\common\model\MerchantCashier;
use app\common\model\OpenTemplate;
use app\common\model\Paylog;
use app\common\model\System;
use app\common\model\WxOpen;
use Wechat\Wxobjopen;

class TemplateMsg extends Wxoption
{

    public function send_tpl($type, $data)
    {
        switch ($type) {
//           case "pay_tz":
//               $data['tpl_type'] = 'pay_tpl';
//               $data['template_id'] = $this->get_tpl_id($data);
//               $res = $this->pay_msg_tomach_ser($data);
//               break;
            case "pay_count":
                $data['tpl_type'] = 'pre_man_tpl';
                $data['template_id'] = $this->get_tpl_id($data);
                $res = $this->pay_count_tomach($data);
                break;
            case "pay_balance":
                $data['tpl_type'] = 'card_ye_tpl';
                $data['template_id'] = $this->get_tpl_id($data);
                $res = $this->balance_change_touser($data);
                break;
            case "put_gift":
                $data['tpl_type'] = 'card_zs_tpl';
                $data['template_id'] = $this->get_tpl_id($data);
                $res = $this->gift_put_touser($data);
                break;
            case "pay":
                $id = $data['merchantid'];
                $orderid = $data['orderid'];
                $res = $this->pay_msg_tomach_ser($id, $orderid);
                break;
            case "pay_user":
                $id = $data['merchantid'];
                $orderid = $data['orderid'];
                $res = $this->pay_msg_touser($id, $orderid);
                break;
            default:
                $res = '';
                break;
        }
        return $res;
    }

//支付成功 通知用户
    private function pay_msg_touser($id, $orderid)
    {

        $Platurl = new Platurl();
        $options = $Platurl->getagenttplmsg($id);

        $weObj = new Wxobjopen($options);
        $mas['orderid'] = $orderid;
        $Paylog = new Paylog();
        $WxOpen = new WxOpen();
        $orderinfo = $Paylog->where($mas)->find();
        $wxopenid = $WxOpen->where(array('authorizer_appid' => $options['authorizer_appid']))->value('id');
        $OpenTemplate = new OpenTemplate();
        $maptpl['wx_open_id'] = $wxopenid;
        $maptpl['type'] = "pay_user_tpl";
        $templateid = $OpenTemplate->where($maptpl)->value('template_id');
        $orderremark = "---------------------\n" .
            "应付金额:" . $orderinfo['yf_price'] . "元\n" .
            "折扣金额:" . $orderinfo['zk_price'] . "元\n" .
            "折扣详情:" . "会员卡折扣:" .
            $orderinfo['dis_card_zk'] . "元;" .
            "会员卡等级折扣：" . $orderinfo['vip_card_zk'] . "元;" .
            "卡券抵扣:" . $orderinfo['gel_card_zk'] . "元(" . $this->getdeduzkinfo($orderinfo['hx_card'], $orderinfo['gel_card_zk']) . ")";


        if ($templateid) {
            $template['touser'] = $orderinfo['sub_openid'];
            $template['template_id'] = $templateid;
            $template['url'] = '';
            $template['topcolor'] = "#7B68EE";
            $template['data']['first'] = ['value' => '您在' . $this->getmerchantname($orderinfo['mid']) . "有一笔订单支付成功", 'color' => "#000000"];
            $template['data']['keyword1'] = ['value' => $orderinfo['orderid'], 'color' => '#FF0000'];
            $template['data']['keyword2'] = ['value' => $orderinfo['pay_time'], 'color' => '#FF0000'];
            $template['data']['keyword3'] = ['value' => $orderinfo['price'] . "元", 'color' => '#FF0000'];
            $template['data']['keyword4'] = ['value' => getpayfs($orderinfo['pay_fs']), 'color' => '#FF0000'];
            $template['data']['remark'] = ['value' => $orderremark, 'color' => '#000000'];
            //发送
//            return $template;
            $res = $weObj->sendTemplateMessage($template);

        }
        return $res;
    }

    //支付通知  向商家  服务商发送
    private function pay_msg_tomach_ser($id, $orderid)
    {
        $Platurl = new Platurl();
        $options = $Platurl->getagenttplmsg($id);
        $weObj = new Wxobjopen($options);
        $mas['orderid'] = $orderid;
        $Paylog = new Paylog();
        $Cashier = new MerchantCashier();
        $pay = $Paylog->where($mas)->find();
        $res = [];
        if ($pay['tzzt'] == 0) {
            $day = strtotime(date('Y-m-d'));
            $tom = strtotime(date('Y-m-d', strtotime('+1 day')));
            $mab['add_time'] = array(array('gt', $day), array('lt', $tom));
            $mab['mid'] = $id;
            $mab['pay_statu'] = 1;
            $sumday = $Paylog->where($mab)->sum('price');       //收款总计
            $wx['pay_fs'] = ['in', [0, 2]];
            $wxday = $Paylog->where($mab)->where($wx)->sum('price');       //微信
            $ali['pay_fs'] = ['in', [1, 3]];
            $aliday = $Paylog->where($mab)->where($ali)->sum('price');       //支付宝
            $xj['pay_fs'] = ['in', [4]];
            $xjday = $Paylog->where($mab)->where($xj)->sum('price');       //现金
            $card['pay_fs'] = ['in', [8]];
            $cardday = $Paylog->where($mab)->where($card)->sum('price');       //会员卡
            $mi['mid'] = $id;
            $mi['is_tz'] = 1;
            $touser = $Cashier->where($mi)->select();
            //获取商户名称及模板ID；
            $map['id'] = $id;
            $Merchant = new Merchant();
            $mach = $Merchant->where($map)->value('merchant');//获取商户名称
            $WxOpen = new WxOpen();
            $wxopenid = $WxOpen->where(array('authorizer_appid' => $options['authorizer_appid']))->value('id');
            $OpenTemplate = new OpenTemplate();
            $maptpl['wx_open_id'] = $wxopenid;
            $maptpl['type'] = "pay_tpl";

            $templateid = $OpenTemplate->where($maptpl)->value('template_id');
            //end
            if ($templateid) {

                switch ($pay['pay_fs']) {
                    case 0:
                        $pay_fs = "微信支付";
                        break;
                    case 1:
                        $pay_fs = "支付宝支付";
                        break;
                    case 2:
                        $pay_fs = "微信刷卡支付";
                        break;
                    case 3:
                        $pay_fs = "支付宝刷卡";
                        break;
                    case 4:
                        $pay_fs = "现金支付";
                        break;
                    case 5:
                        $pay_fs = "pos支付";
                        break;
                    case 8:
                        $pay_fs = "微信会员卡支付";
                        break;
                    default:
                        $pay_fs = "其他方式支付";

                }

                $gel_info = getdeduzkinfo($pay['hx_card'], $pay['gel_card_zk']) . getdiszkinfo($pay['dis_card_zk']) . getvipzkinfo($pay['vip_card_zk']);
                foreach ($touser as $v) {
                    if ($v['is_tz'] == 1) {
                        $template = array(
                            'touser' => $v['openid'],
                            'template_id' => $templateid,
//                    'url' => "https://wxpay.weilinzhou.com/admin.php?s=/Authlogin/login/fs/paydetail/payid/" . $pay['id'],
                            'url' => '',
                            'topcolor' => "#7B68EE",
                            'data' => array(
                                'first' => array('value' => $mach . "收款提醒", 'color' => "#743A3A"),
                                'keyword1' => array('value' => $pay['price'] . "元", 'color' => '#FF0000'),
                                'keyword2' => array('value' => $pay_fs, 'color' => '#000'),
                                'keyword3' => array('value' => date("Y-m-d H:i:s", $pay['add_time']), 'color' => '#000'),
                                'keyword4' => array('value' => $pay['orderid'], 'color' => '#000'),
                                'remark' => array('value' =>
                                    "---------------------\n" .
                                    "微 信  支 付:" . $wxday . "元\n" .
                                    "支付宝支付:" . $aliday . "元\n" .
                                    "现 金  支 付:" . $xjday . "元\n" .
                                    "会员卡支付:" . $cardday . "元\n" .
                                    "---------------------\n" .
                                    "当日累计收款:" . $sumday . "元\n" .
                                    "---------------------",
                                    'color' => '#000'),
                            )
                        );

                        $res[] = $weObj->sendTemplateMessage($template);

                    }
                }
                $sdata['tzzt'] = 1;
                $sdata['tzmsg'] = json_encode($res);
                $Paylog->save($sdata, $mas);
            } else {
                $res = array('code' => "9999", 'message' => "未设置模板消息");
            }
        }
        //END
        $AfterPayPutCard = new AfterPayPutCard();
        $AfterPayPutCard->paymentcard($orderid);
        return $res;
    }

    public function sendtemplate($id, $orderid)
    {


    }

    //经营报表  向商家 商家发送
    /*
     * openid  card_id  template_id  keyword1  remark
     *
     * */
    private function pay_count_tomach($data)
    {
        $options = $this->options($data['card_id'], 'card_id');
        $weObj = new Wxobjopen($options);
        $templateid = $data['template_id'];
        $template['touser'] = $data['openid'];
        $template['template_id'] = $templateid;
        $template['url'] = '';
        $template['topcolor'] = "#7B68EE";
        $template['data']['first'] = ['value' => '请查收昨日会员卡运营数据', 'color' => "#000000"];
        $template['data']['keyword1'] = ['value' => $data['keyword1'], 'color' => '#FF0000'];
        $template['data']['keyword2'] = ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000000'];
        $template['data']['remark'] = ['value' => $data['remark'], 'color' => '#000000'];
        //发送
        $res = $weObj->sendTemplateMessage($template);
        if ($res['errcode'] == 0) {
            $rarr = $res;
        } else {
            $rarr = $res;
        }
        return $rarr;
    }

    //余额变动  向用户 商家发送
    /*
     * card_id  template_id  type add_balance balance  openid
     * */
    private function balance_change_touser($arr)
    {
        //初始化微信类
        $options = $this->options($arr['card_id'], 'card_id');
        $wxObj = new Wxobjopen($options);
        $templateid = $arr['template_id'];
        switch ($arr['type']) {
            case "1":
                $type = "充值";
                break;
            case "2":
                $type = "消费";
                break;
            case "3":
                $type = "同步";
                break;
            default:
                $type = "未知";
                break;
        }
        $add_balance = $arr['add_balance'];
        $balance = $arr['balance'];
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => trim($templateid),
            'url' => "",
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => '余额' . $type . "提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'keyword2' => ['value' => '余额' . $type, 'color' => '#FF0000'],
                'keyword3' => ['value' => $add_balance . '元', 'color' => '#000'],
                'keyword4' => ['value' => $balance . '元', 'color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );
        $res = $wxObj->sendTemplateMessage($template);
        $CardUserGet = new CardUserGet();
        $arrp['card_id'] = $arr['card_id'];
        $arrp['code'] = $CardUserGet->where(['openid' => $arr['openid'], 'card_id' => $arr['card_id']])->value('code');
        $arrp['price'] = $balance;
        $Combalance = new Balance();
        $resu = $Combalance->updatebalance($arrp);
        if ($res['errcode'] == 0) {
            $rarr = $resu;
        } else {
            $rarr = $res;
        }

        return $rarr;
    }

    //礼品发放  向用户 由商家发送
    /*
     * openid   template_id  card_id  name   title  rec_id
     * */
    private function gift_put_touser($arr)
    {
//        if ($arr['card_id']){
//            $options = $this->options($arr['card_id']);
//        }else{
        $options = $this->options($arr['mid'], 'mid');
//        }

        $wxObj = new Wxobjopen($options);
        $Platurl = new Platurl();
        $notify_url = $Platurl->getagenturl('mid', $arr['mid']);
        switch ($arr['type']) {
            case "fire":
                $url = $notify_url . $arr['url'];
                $remark = $this->givecards($arr['give_id'], $arr['type']);
                break;
            case "paycard":
                $url = $notify_url . $arr['url'];
                $remark = $this->givecards($arr['give_id'], $arr['type']);
                break;
            default:
                $url = $notify_url . '/mobile.php?s=/cardget/getcards/mid/' . $arr['mid'] . '/rec_id/' . $arr['rec_id'];
                $remark = $this->givecards($arr['rec_id'], $arr['type']);
                break;
        }
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => $arr['template_id'],
            'url' => $url,
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => "卡券赠送提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => $arr['name'], 'color' => '#000'],
                'keyword2' => ['value' => $arr['title'], 'color' => '#FF0000'],
                'keyword3' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'remark' => ['value' => $remark, 'color' => '#000'],
            )
        );
//        file_put_contents('/data2/html/payos/test.txt', 'msg-1' . json_encode($template), FILE_APPEND);
//        file_put_contents('/data2/html/payos/test.txt', 'msg-2' . json_encode($remark), FILE_APPEND);
        //发送
        $res = $wxObj->sendTemplateMessage($template);
        if ($res['errcode'] == 0) {
            $rarr = $res;
        } else {
            $rarr = $res;
        }
        return $rarr;
    }

    //获取模板ID
    private function get_tpl_id($arr)
    {
        if ($arr['card_id']) {
            $mid = $this->get_mid($arr['card_id']);
        } else {
            $mid = $arr['mid'];
        }

        $wx_openid = $this->get_wxopen_id($mid);
        $OpenTemplate = new OpenTemplate();
        $templateid = $OpenTemplate->where(['type' => $arr['tpl_type'], 'wx_open_id' => $wx_openid])->value('template_id');
        return $templateid;
    }

    //获取模板ID
    private function get_wxopen_id($mid)
    {
        $Merchant = new \app\common\model\Merchant();
        $wx_open_id = $Merchant->where(['id' => $mid])->value('wx_open_id');
        return $wx_open_id;
    }

    //获取mid
    private function get_mid($card_id)
    {
        $CardMember = new CardMember();
        $mid = $CardMember->where(['card_id' => $card_id])->value('mid');
        return $mid;
    }


    //获取规则赠券
    private function givecards($rec_id, $type = '')
    {
        switch ($type) {
            case "fire":
                $CardGive = new CardGive();
                $zs_card_all = $CardGive->where(['id' => $rec_id])->value('card_id_list');
                $res = getgivecardnew($zs_card_all, 0);
                break;
            case "paycard":
                $CardPaycard = new CardPaycard();
                $zs_card_all = $CardPaycard->where(['id' => $rec_id])->value('cardlist');
                $res = getpaygive($zs_card_all);
                break;
            default:
                $CardCzLog = new CardCzLog();
                $CardCzgive = new CardCzgive();
                $give_id = $CardCzLog->where(['id' => $rec_id])->value('giveid');
                $zs_card_all = $CardCzgive->where(['id' => $give_id])->value('zs_card_id_all');
                $res = getgivecardnew($zs_card_all, 0);
        }

        return $res;
    }
}